<template>
	<div>
		<div class="container">
			<div class="tableBar">
				<el-input placeholder="请输入内容" v-model="fileName" suffix-icon="el-icon-search" size="small"
					class="smallInput" clearable>
				</el-input>
				<el-button type="primary" icon="el-icon-search" size="small" @click="searchHandle">搜索</el-button>
				<el-button type="primary" @click="showDialog()" size="small">
					上传文件
					<i class="el-icon-upload el-icon--right"></i>
				</el-button>
				<el-button type="danger" size="small" @click="deleteHandle">
					批量删除
					<i class="el-icon-delete"></i>
				</el-button>
			</div>
			<el-table :data="dataList" stripe class="tableBox" @selection-change="handleSelectionChange">>
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column type="index" :index="indexMethod">
				</el-table-column>
				<el-table-column prop="fileName" label="文件名称"></el-table-column>
				<el-table-column prop="fileSize" label="文件大小">
					<template #default="scope">
						<span>{{(scope.row.fileSize/1024).toFixed(2)}} kb</span>
					</template>
				</el-table-column>
				<el-table-column prop="uploadTime" label="上传时间"></el-table-column>
				<el-table-column label="操作" width="160" align="center">
					<template slot-scope="scope">
						<el-button type="text" size="small" class="blueBug"
							@click="download(scope.row.fileId,scope.row.fileName)">
							下载
						</el-button>
						<el-button type="text" size="small" class="blueBug" @click="deletefile(scope.row.fileId)">
							删除
						</el-button>
						<el-button type="text" size="small" class="blueBug" @click="sharefile(scope.row.fileId)">
							分享
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination align="right" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
				:current-page="pageIndex" :page-sizes="[10, 20, 50]" :page-size="pageSize" :total="totalCount"
				layout="total, sizes, prev, pager, next, jumper"></el-pagination>
			
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				fileName: "",
				dataList: [],
				pageIndex: 1,
				pageSize: 10,
				totalCount: 0,
				multipleSelection: []
			}
		},
		methods: {
			loadDataList: function() {
				let that = this;
				if(that.fileName == ""){
					that.fileName=null;
				}
				let data = {
					pageIndex: that.pageIndex,
					pageSize: that.pageSize,
					fileName: that.fileName
				};
				let config = {
					headers: {
						'Content-Type': 'application/json'
					},
					data: data
				};
				that.axios.post('api/files/',data,config).then((resp) => {
					let result = resp.data;
					if (result.code == 200) {
						for(let one of result.data.list){
							one.uploadTime = that.dayjs(one.uploadTime).format("YYYY-MM-DD HH:mm:ss");
						}
						that.dataList = result.data.list;
						that.totalCount = result.data.totalCount;
					}
				});
			},
			showDialog: function() {
				let input = document.createElement("input");
				input.type = "file";
				input.setAttribute("ref", "fileInput");
				input.style.display = "none";
				// 将新创建的元素添加到 DOM 树中
				document.body.appendChild(input);

				input.onchange = function(e) {
					const file = e.target.files[0];
					const formData = new FormData();
					formData.append('file', file);
					formData.append('userId', '1');
					fetch('/api/files/upload', {
						method: 'POST',
						body: formData,
					}).then(function(response) {
						if (response.ok && response.status === 200) {
							return response.json();
						} else {
							throw new Error('上传失败');
						}
					}).then(function(data) {
						if (data.code === 202) {
							location.reload();
						} else {
							console.log("上传失败");
						}
					}).catch(function(error) {
						console.error('发生错误：', error);
					})

				}

				input.click();


				document.body.removeChild(input);
			},
			download: function(id, fileName) {
				this.axios({
					url: `/api/files/download?fileId=${id}`,
					method: `GET`,
					responseType: `blob`
				}).then(response => {
					const url = window.URL.createObjectURL(new Blob([response.data]));
					const link = document.createElement('a');
					link.href = url;
					link.download = fileName;
					link.click();
				})
			},
			deletefile(id) {
				this.axios({
					url: `/api/files/${id}`,
					method: `DELETE`,
				}).then(resp => {
					if (resp.data.code == 203) {
						this.$message({
							message: resp.data.message,
							type: 'success',
							duration: 1200
						});
						location.reload();
					}
				})
			},
			sharefile(id) {
				this.axios({
					url: `/api/files/share/${id}`,
					method: `GET`,
				}).then(resp => {

					this.$alert(resp.data.data.url)

				}).catch(error => console.log(error));

			},
			indexMethod(index) {
				return index + 1;
			},
			handleSelectionChange: function(val) {
				this.multipleSelection = val;
			},
			sizeChangeHandle: function(val) {
				this.pageSize = val;
				this.pageIndex = 1;
				this.loadDataList();
			},
			currentChangeHandle: function(val) {
				this.pageIndex = val;
				this.loadDataList();
			},
			searchHandle: function(){
				if(this.fileName != ""){
					this.loadDataList();
				}
			},
			deleteHandle: function(){
				let that = this;
				let ids = that.multipleSelection.map(item => {
					return item.fileId;
				});
				let data = {
					ids: ids
				}
				console.log(ids);
				let config = {
					data: data
				};
				that.axios.delete('/api/files/deleteFileByIds',config).then(resp => {
					if(resp.data.data > 0){
						that.$message({
							message: '操作成功',
							type: 'success',
							duration: 1200
						});
						that.loadDataList();
					}else{
						that.$message({
							message: '未能成功删除这些记录',
							type: 'warning',
							duration: 1200
						});
					}
				})
			}

		},
		created: function() {
			this.loadDataList();
		}
	}
</script>

<style>
	.tableBar {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.tableBar>* {
		margin-right: 16px;
		/* 设置元素之间的右边距为 16 像素 */
	}

	.tableBar el-button {
		margin-right: 20px;
	}

	.smallInput {
		width: 150px;
	}
</style>